using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using WordDocument = DocumentFormat.OpenXml.Wordprocessing.Document;

namespace DocumentCreationSystem.Views
{
    public partial class OutlineGenerationDialog : Window
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<OutlineGenerationDialog> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IDocumentService _documentService;
        
        public string? GeneratedOutline { get; private set; }
        public bool IsConfirmed { get; private set; }
        public string? ReferenceContent { get; set; }
        public Project? CurrentProject { get; set; }

        public OutlineGenerationDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<OutlineGenerationDialog>>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _documentService = serviceProvider.GetRequiredService<IDocumentService>();
            
            InitializeDialog();
        }

        private void InitializeDialog()
        {
            // 设置参考内容
            if (!string.IsNullOrEmpty(ReferenceContent))
            {
                ReferenceContentTextBox.Text = ReferenceContent.Length > 500 
                    ? ReferenceContent.Substring(0, 500) + "..." 
                    : ReferenceContent;
                
                var wordCount = CountWords(ReferenceContent);
                ReferenceStatsTextBlock.Text = $"参考内容：{wordCount}字，{ReferenceContent.Length}字符";
            }
            else
            {
                UseReferenceContentCheckBox.IsChecked = false;
                ReferenceContentCard.Visibility = Visibility.Collapsed;
            }

            // 绑定事件
            UseReferenceContentCheckBox.Checked += (s, e) => 
                ReferenceContentCard.Visibility = Visibility.Visible;
            UseReferenceContentCheckBox.Unchecked += (s, e) => 
                ReferenceContentCard.Visibility = Visibility.Collapsed;
        }

        private async void Generate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(BookTitleTextBox.Text))
                {
                    MessageBox.Show("请输入书籍名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(CreativeDirectionTextBox.Text))
                {
                    MessageBox.Show("请输入创作方向", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                UpdateStatus("正在生成大纲...", true);
                GenerateButton.IsEnabled = false;

                var outline = await GenerateOutlineAsync();
                
                if (!string.IsNullOrEmpty(outline))
                {
                    GeneratedOutline = outline;
                    
                    // 自动保存到项目文件夹
                    if (AutoSaveCheckBox.IsChecked == true && CurrentProject != null)
                    {
                        await SaveOutlineToProject(outline);
                    }
                    
                    IsConfirmed = true;
                    UpdateStatus("大纲生成完成", false);
                    
                    MessageBox.Show("大纲生成成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DialogResult = true;
                    Close();
                }
                else
                {
                    UpdateStatus("大纲生成失败", false);
                    MessageBox.Show("大纲生成失败，请重试", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成大纲时发生错误");
                UpdateStatus("生成失败", false);
                MessageBox.Show($"生成大纲时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                GenerateButton.IsEnabled = true;
            }
        }

        private async Task<string> GenerateOutlineAsync()
        {
            var bookTitle = BookTitleTextBox.Text.Trim();
            var creativeDirection = CreativeDirectionTextBox.Text.Trim();
            var targetChapters = int.TryParse(TargetChaptersTextBox.Text, out var chapters) ? chapters : 100;
            var wordsPerChapter = int.TryParse(TargetWordsPerChapterTextBox.Text, out var words) ? words : 6500;
            var volumeCount = int.TryParse(VolumeCountTextBox.Text, out var volumes) ? volumes : 10;
            var detailLevel = OutlineDetailComboBox.SelectedIndex;

            var prompt = BuildOutlinePrompt(bookTitle, creativeDirection, targetChapters, wordsPerChapter, volumeCount, detailLevel);
            
            var maxTokens = detailLevel switch
            {
                0 => 3000,  // 简要大纲
                1 => 5000,  // 详细大纲
                2 => 8000,  // 超详细大纲
                _ => 5000
            };

            return await _aiService.GenerateTextAsync(prompt, maxTokens, 0.8f);
        }

        private string BuildOutlinePrompt(string bookTitle, string creativeDirection, int targetChapters, int wordsPerChapter, int volumeCount, int detailLevel)
        {
            var detailDescription = detailLevel switch
            {
                0 => "简要概述",
                1 => "详细描述",
                2 => "超详细分析，包含具体情节点和角色发展",
                _ => "详细描述"
            };

            var referenceInfo = "";
            if (UseReferenceContentCheckBox.IsChecked == true && !string.IsNullOrEmpty(ReferenceContent))
            {
                referenceInfo = $@"

参考内容：
{ReferenceContent}

请结合以上参考内容进行大纲创作，保持风格和设定的一致性。";
            }

            return $@"请为以下小说项目生成一个{detailDescription}的全书大纲：

书籍信息：
- 标题：{bookTitle}
- 创作方向：{creativeDirection}
- 目标章节数：{targetChapters}章
- 每章字数：{wordsPerChapter}字
- 分卷数量：{volumeCount}卷{referenceInfo}

请生成包含以下内容的全书大纲：
1. 故事背景和世界观设定
2. 主要角色介绍和关系网络
3. 核心冲突和主线情节
4. 分卷结构规划（共{volumeCount}卷）
5. 每卷的主要情节和发展脉络
6. 重要情节点和转折点
7. 角色成长弧线
8. 预期的高潮和结局

请确保大纲具有足够的深度和细节，能够支撑{targetChapters}章的长篇创作，并且各卷之间有清晰的逻辑关系和递进发展。";
        }

        private async Task SaveOutlineToProject(string outline)
        {
            try
            {
                if (CurrentProject == null) return;

                var fileName = $"{BookTitleTextBox.Text.Trim()}_大纲.docx";
                var outlinePath = Path.Combine(CurrentProject.RootPath, "大纲");
                
                // 确保目录存在
                if (!Directory.Exists(outlinePath))
                {
                    Directory.CreateDirectory(outlinePath);
                }

                var fullPath = Path.Combine(outlinePath, fileName);
                
                // 创建docx文件
                await CreateOutlineDocxAsync(fullPath, outline);
                
                // 创建文档记录
                await _documentService.CreateDocumentAsync(CurrentProject.Id, fileName, outline);
                
                UpdateStatus($"大纲已保存到：{fileName}", false);
                _logger.LogInformation($"大纲已保存到项目文件夹：{fullPath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存大纲到项目文件夹失败");
                UpdateStatus("保存大纲失败", false);
            }
        }

        private async Task CreateOutlineDocxAsync(string filePath, string content)
        {
            await Task.Run(() =>
            {
                using var document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
                var mainPart = document.AddMainDocumentPart();
                mainPart.Document = new WordDocument();
                var body = mainPart.Document.AppendChild(new Body());

                // 添加标题
                var titleParagraph = new Paragraph();
                var titleRun = new Run();
                var titleText = new Text($"{BookTitleTextBox.Text.Trim()} - 创作大纲");
                titleRun.AppendChild(titleText);
                titleParagraph.AppendChild(titleRun);
                body.AppendChild(titleParagraph);

                // 添加空行
                body.AppendChild(new Paragraph());

                // 添加内容
                var paragraphs = content.Split('\n', StringSplitOptions.None);
                foreach (var paragraphText in paragraphs)
                {
                    var paragraph = new Paragraph();
                    var run = new Run();
                    run.AppendChild(new Text(paragraphText));
                    paragraph.AppendChild(run);
                    body.AppendChild(paragraph);
                }
            });
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            IsConfirmed = false;
            DialogResult = false;
            Close();
        }

        private void UpdateStatus(string message, bool showProgress)
        {
            StatusTextBlock.Text = message;
            ProgressBar.Visibility = showProgress ? Visibility.Visible : Visibility.Collapsed;
        }

        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            // 中文字符计数
            var chineseCharCount = System.Text.RegularExpressions.Regex.Matches(text, @"[\u4e00-\u9fa5]").Count;
            
            // 英文单词计数
            var englishWords = System.Text.RegularExpressions.Regex.Matches(text, @"\b[a-zA-Z]+\b").Count;
            
            return chineseCharCount + englishWords;
        }
    }
}
